package room_event

import (
	"fmt"
	global2 "longmen/server/config/global"
	"longmen/server/internal/rpc/tencentim/cache"
	"longmen/server/internal/rpc/tencentim/imsdk"
	messages2 "longmen/server/internal/rpc/tencentim/messages"
	"longmen/server/pkg/common/helper/const"
	"longmen/server/pkg/db/mysql/models/models_live"
	"sync"
	"time"
)

var roomLiveMap sync.Map

type RoomHeatMessage struct {
	messages2.SentMessageStruct
	Val              int `json:"val"`
	Status           int `json:"status"`
	BarrageTimeCount int `json:"barrage_time_count"`
}

// 最多允许30线程并发
var roomStatusHeatCh = make(chan struct{}, 30)

// SyncRoomStatusAndHeat 定时任务广播数据
func SyncRoomStatusAndHeat() {
	for {
		rooms := GetLiveRoom()
		if len(rooms) == 0 {
			time.Sleep(time.Second * 3)
		}
		wg := sync.WaitGroup{}
		for _, roomId := range rooms {
			global2.Log.Debugf("ROOM[%d]: start process", roomId)
			roomStatusHeatCh <- struct{}{}
			wg.Add(1)
			go func(rid int) {
				defer func() {
					wg.Done()
				}()
				handlingHeatMessage(rid)
				<-roomStatusHeatCh
			}(roomId)
		}
		wg.Wait()
		time.Sleep(time.Second * 10)
	}
}

func GetLiveRoom() []int {
	var anchorIds []int
	global2.Live().Model(&models_live.Live{}).Select("anchorid").Find(&anchorIds)
	global2.Log.Debugf("GetLiveRoom ids:%v", anchorIds)
	return anchorIds
}
func HandlingRoomHeat(roomID int) {
	handlingHeatMessage(roomID)
}

func handlingHeatMessage(roomID int) {
	status, err := checkLiveConfigStatus(roomID)
	if err != nil {
		return
	}
	rep := RoomHeatMessage{
		SentMessageStruct: messages2.SentMessageStruct{
			Type: messages2.HeatReplyMessageType,
		},
		Val:              int(cache.NewRoomHeat(roomID).GetHeatTotal()),
		Status:           status,
		BarrageTimeCount: int(cache.NewRoomHeat(roomID).GetFieldValue(_const.RoomStatsBarrageTimeCount)),
	}
	imsdk.GetSdk().BroadcastInterface(roomID, rep, 3)
	return
}

func checkLiveConfigStatus(roomId int) (status int, err error) {
	roomCfg, err := cache.GetLiveConfig(roomId)
	if err != nil {
		return 0, fmt.Errorf("ROOM[%d]: check models_live config status failed, %s", roomId, err)
	}
	return int(roomCfg.Status), nil
	//var isLive bool
	//liveCfg := roomCfg.Status == messages.RoomConfigStatusLive
	//value, ok := roomLiveMap.Load(roomId)
	//if !ok || value == nil {
	//	isLive = false
	//} else {
	//	isLive = value.(bool)
	//}
	//statsAllFields := []string{
	//	util.RoomStatsActiveViewer,           // 活跃观众
	//	string(util.PopMsgCount),             // 弹幕消息
	//	string(util.RoomStatsGiftTotalPrice), // 礼物价值
	//}
	//key := cache2.GenStatsCacheKey(roomId)
	//rdc := models.GetRds()
	//if liveCfg && !isLive {
	//	// 如果远程配置为直播，而房间还未开始直播，则启动直播
	//	p := rdc.Pipeline()
	//	for _, f := range statsAllFields {
	//		//global.Log.Debugf("ROOM[%d]: %s:%s init : 0 ", roomId, key, f)
	//		p.HSet(key, f, 0)
	//		p.Expire(key, timehelper.Second*86400*7)
	//	}
	//	_, err := p.Exec()
	//	if err != nil {
	//		global.Log.Errorf("ROOM[%d]: start models_live failed, %s", roomId, err)
	//	} else {
	//		roomLiveMap.Store(roomId, true)
	//	}
	//} else if !liveCfg && isLive {
	//	// 如果远程配置为关闭直播，而房间处于直播中，则关闭直播
	//	// 清理缓存数据
	//	_ = rdc.Del(key).Err()
	//	global.Log.Debugf("ROOM[%d]:close models_live, %s", roomId, err)
	//	roomLiveMap.Store(roomId, false)
	//}
	//
	//// 广播房间的当前状态
	//m := &messages.RoomStatusMessage{
	//	SentMessageStruct: messages.SentMessageStruct{Type: messages.RoomStatusMessageType},
	//	Status:            roomCfg.Status,
	//}
	//// 如果直播结束，聊天记录清除
	//if m.Status == messages.RoomConfigStatusLiveEnd {
	//	cache.DeleteHeatMap(roomId)
	//	GetChatHistory(roomId).DeleteChatHistory(0, messages.ClearHisCloseType)
	//}
	//
	////global.Log.Infof("ROOM[%d]: 远程直播配置: %t, 房间直播状态: %t", r.id, liveCfg, r.models_live)
	//return int(roomCfg.Status), nil
}
